﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Collections;

namespace NuGet.Enterprise.Server.Configuration
{
    public sealed class BuildStoreConnectionCollection
        : ConfigurationElementCollection, IEnumerable, IEnumerable<BuildStoreConnectionSettings>
    {
        [ConfigurationProperty("defaultConnection", IsRequired = false, IsKey = false)]
        public string DefaultConnectionName
        {
            get { return (string)base["defaultConnection"]; }
            set { base["defaultConnection"] = value; }
        }

        public BuildStoreConnectionSettings DefaultConnectionSettings
        {
            get { return (string.IsNullOrEmpty(this.DefaultConnectionName) ? null : this[this.DefaultConnectionName]); }
        }

        public BuildStoreConnectionSettings this[int index]
        {
            get 
            {
                var proxy = base.BaseGet(index) as BuildStoreConnectionProxy;

                return (proxy == null ? null : proxy.Instance) as BuildStoreConnectionSettings;
            }
        }

        public new BuildStoreConnectionSettings this[string key]
        {
            get
            {
                key = key ?? DefaultConnectionName;

                var proxy = base.BaseGet(key) as BuildStoreConnectionProxy;

                return (proxy == null ? null : proxy.Instance) as BuildStoreConnectionSettings;
            }
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new BuildStoreConnectionProxy();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((BuildStoreConnectionProxy)element).Name;
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get
            {
                return ConfigurationElementCollectionType.AddRemoveClearMap;
            }
        }

        public new IEnumerator GetEnumerator()
        {
            return new BuildStoreConnectionEnumerator(this);
        }

        IEnumerator<BuildStoreConnectionSettings> IEnumerable<BuildStoreConnectionSettings>.GetEnumerator()
        {
            return new BuildStoreConnectionEnumerator(this);
        }
    }
}